//
// Created by Andy on 2025/8/12.
//

#include <QDebug>
#include "can_intarface.h"

can_intarface::can_intarface() {
    this->can_port_num = CAN_ScanDevice();
    this->current_can_port = -1;
    this->open_port(0);
    CAN_Reset(0);

    // start recv and send thread
    recv = new recv_thread;
    connect(recv, SIGNAL(receivemsg(Can_Msg*, int)), this, SLOT(readcan(Can_Msg*, int)), Qt::DirectConnection);

    send_frame(0, 1);
}

int can_intarface::get_port(void) {
    return can_port_num;
};

can_intarface::~can_intarface() {
    close_port();
}

int can_intarface::open_port(int idx) {
    this->current_can_port = idx;
    return CAN_OpenDevice(idx);
}

int can_intarface::close_port(void) {
    int ret = CAN_CloseDevice(this->current_can_port);
    this->current_can_port = -1;
    return ret;
}

void can_intarface::readcan(Can_Msg *rmgs,int lenth)
{
    qDebug("can recv");
}

int can_intarface::send_frame(int idx, uint8_t data) {
    float a = 0.3;
    uint8_t *p = (uint8_t *)&a;
    Can_Msg tmsg;
    tmsg.ID = 0x00000003;
    tmsg.ExternFlag = 0;
    tmsg.DataLen = 4;
    tmsg.Data[0] = p[0];
    tmsg.Data[1] = p[1];
    tmsg.Data[2] = p[2];
    tmsg.Data[3] = p[3];
    return CAN_Transmit(idx, &tmsg, 1, 200);
}

recv_thread::recv_thread() {

}

recv_thread::~recv_thread() {

}

void recv_thread::run(void) {
    int length;
    this->breakout = 1;
    while(this->breakout) {
        length = CAN_Receive(0, rmgs, 100, 1000);
        if(length <= 0)
            continue;
        emit receivemsg(rmgs, length);
    }
}

void recv_thread::stop(void) {
    this->breakout = 0;
}
